package org.databandtech.logmock.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

import org.databandtech.logmock.entity.Person;

import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;

public class Csv<T> {
	
	public static <T> void writeCSV(List<T> dataList, String filePath) {
		try {
			
			File file=new File(filePath);   

			if(!file.exists())   
			{   
			    mkdirAndFile(filePath);   
			}
			
			Writer writer = new FileWriter(filePath);
			writer.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }));
			
			StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
					.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
					.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
					.withEscapechar('\\').build();
			beanToCsv.write(dataList);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (CsvDataTypeMismatchException e) {
			e.printStackTrace();
		} catch (CsvRequiredFieldEmptyException e) {
			e.printStackTrace();
		}
		System.out.println(filePath + "数据导出成功");
	}
	
	public static void mkdirs(String path) {
        File f;
        try {
            f = new File(path);
            if (!f.exists()) {
                boolean i = f.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
	 public static void mkdirAndFile(String path) {
	        File f;
	        try {
	            f = new File(path);
	            if (!f.exists()) {
	                boolean i = f.getParentFile().mkdirs();

	            }
	            boolean b = f.createNewFile();

	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }


}
